<template>
  <!-- 根标签 -->
  <div>
    <!-- 上方搜索框 -->
    <el-card style="height: 50px" :body-style="{ padding: '10px', height: '50px', width: '100%'}">
      <div class="box-card-div">
        <el-form :inline="true" :model="orderItemDTO" ref="orderItemForm" class="demo-form-inline">
          <!-- 搜索订单编号 -->
          <el-form-item label="订单编号" prop="orderId" width="80px">
            <el-input size="small" v-model="orderItemDTO.orderId" placeholder="请输入订单编号"></el-input>
          </el-form-item>
          <!-- 搜索商品编号 -->
          <el-form-item label="商品编号" prop="productId">
            <el-input size="small" v-model="orderItemDTO.productId" placeholder="请输入商品编号"></el-input>
          </el-form-item>
          <!-- 搜索商品名称 -->
          <el-form-item label="商品名称" prop="productName">
            <el-input size="small" v-model="orderItemDTO.productName" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <!-- 搜索创建时间 -->
          <el-form-item label="创建时间" prop="createdAt">
            <el-date-picker
              size="small"
              v-model="orderItemDTO.createdAt"
              type="datetime"
              placeholder="订单创建时间"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
          <!-- 按钮区域 -->
          <el-form-item class="button-group" style="margin-top: 0px; margin-bottom: 0px;">
            <el-button
              type="success"
              round
              size="small"
              @click="onSearch"
              icon="el-icon-search"
            >
              查询
            </el-button>
            <el-button
              type="warning"
              round
              size="small"
              @click="resetOrderItemForm('orderItemForm')"
              icon="el-icon-refresh-left"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 添加和批量删除按钮 -->
    <div class="button-container">
      <el-button class="btn_add" type="primary" @click="handleAddOrderItem" size="middle" icon="el-icon-plus">新增
      </el-button>
      <el-button class="btb_del" type="danger" @click="deleteOrderItemBatch" size="middle" icon="el-icon-delete">
        批量删除
      </el-button>
      <el-button class="btb_del" type="primary" @click="uploadExcelDialog = true" size="middle" icon="el-icon-delete">
        导入
      </el-button>
      <el-button class="btb_del" type="warning" @click="exportOrderItem" size="middle" icon="el-icon-delete">导出
      </el-button>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="editDialogVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="orderItemForm" :model="orderItem" :rules="rules" label-width="100px">
        <!-- 添加订单编号 -->
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="orderItem.orderId" placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <!-- 添加商品编号 -->
        <el-form-item label="商品编号" prop="productId">
          <el-input v-model="orderItem.productId" placeholder="请输入商品编号"></el-input>
        </el-form-item>
        <!-- 添加商品名称 -->
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="orderItem.productName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <!-- 添加库存id -->
        <el-form-item label="库存id" prop="skuId">
          <el-input v-model="orderItem.skuId" placeholder="请输入库存id"></el-input>
        </el-form-item>
        <!-- 添加数量 -->
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="orderItem.quantity" placeholder="请输入数量"></el-input>
        </el-form-item>
        <!-- 添加单价 -->
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="orderItem.unitPrice" placeholder="请输入单价"></el-input>
        </el-form-item>
        <!-- 添加总金额 -->
        <el-form-item label="总金额" prop="totalPrice">
          <el-input v-model="orderItem.totalPrice" placeholder="请输入总金额"></el-input>
        </el-form-item>
        <!-- 添加创建时间 -->
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker
            v-model="orderItem.createdAt"
            type="date"
            placeholder="订单创建时间"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetOrderItemForm('orderItemForm')">取 消</el-button>
        <el-button type="primary" @click="saveOrderItem('orderItemForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog
      title="上传订单数据"
      width="26%"
      :visible.sync="uploadExcelDialog"
      :close-on-click-modal="false"
    >
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="beforeUpload"
        :file-list="fileList"
        :http-request="uploadExcelOrderItem"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadExcelDialog = false">取 消</el-button>
        <el-button type="primary" @click="uploadExcelOrderItem">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情表格 -->
    <el-card class="orderItem-list">
      <el-table
        :data="tableData"
        border
        class="orderItem-table"
        style="width: 100%"
        height="500"
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 展示复选框 -->
        <el-table-column type="selection" width="30px"></el-table-column>
        <!-- 展示编号 -->
        <el-table-column prop="id" label="编号" width="50px"></el-table-column>
        <!-- 展示订单id -->
        <el-table-column prop="orderId" label="订单id" width="80px"></el-table-column>
        <!-- 展示商品id -->
        <el-table-column prop="productId" label="商品id" width="80px"></el-table-column>
        <!-- 展示商品名称 -->
        <el-table-column prop="productName" label="商品名称" width="200px"></el-table-column>
        <!-- 展示库存id -->
        <el-table-column prop="skuId" label="库存id" width="80px"></el-table-column>
        <!-- 展示数量 -->
        <el-table-column prop="quantity" label="数量" width="80px"></el-table-column>
        <!-- 展示单价 -->
        <el-table-column prop="unitPrice" label="单价" width="80px"></el-table-column>
        <!-- 展示总金额 -->
        <el-table-column prop="totalPrice" label="总金额" width="80px"></el-table-column>
        <!-- 展示创建时间 -->
        <!-- 展示订单提交时间 -->
        <el-table-column prop="createdAt" label="创建时间" width="180px">
          <template slot-scope="scope">
            <span v-if="scope.row.createdAt">{{ scope.row.createdAt }}</span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <!-- 展示操作按钮 -->
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-edit"
              @click="handleOrderItemEdit(scope.$index, scope.row)"
              style="margin-right: 5px; margin-bottom: 2px"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleOrderItemDelete(scope.$index, scope.row)"
              style="margin-bottom: 2px"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <!-- 分页导航 -->
        <div class="pagination-container" style="display: flex; justify-content: flex-end; margin-top: 10px;">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="pageSizes"
            :page-size="orderItemDTO.pageSize"
            :current-page="orderItemDTO.pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
          <!-- 添加一个跳转按钮 -->
          <el-button style="margin-right: 10px" size="small" type="primary" @click="toPage">跳转</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  addOrderItem,
  deleteOrderItem,
  deleteOrderItemBatch,
  fuzzyQueryOrderItem,
  uploadExcel
} from '@/api/order/orderItem'
export default {
  name: 'OrderItem',
  data() {
    return {
      tableData: [],
      orderItem: {},
      orderItemDTO: {
        orderId: '',
        productId: '',
        productName: '',
        createdAt: null,
        pageNum: 1,
        pageSize: 3
      },
      pageSizes: [3, 5, 10, 20],
      total: 0,
      multipleSelection: [],
      title: '添加订单详情',
      editDialogVisible: false,
      rules: {
        orderId: [
          { required: true, message: '请输入订单编号', trigger: 'blur' }
        ],
        productId: [
          { required: true, message: '请输入商品编号', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        skuId: [
          { required: true, message: '请输入库存id', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: '请输入单价', trigger: 'blur' }
        ],
        totalPrice: [
          { required: true, message: '请输入总金额', trigger: 'blur' }
        ],
        createdAt: [
          { required: true, message: '请选择创建时间', trigger: 'change' }
        ]
      },
      fileList: [],
      file: null,
      uploadExcelDialog: false,

    }
  },
  methods: {
    onSearch(){
      this.findAll();
    },
    // 模糊查询+分页处理
    findAll() {
      /**格式化日期*/
      const formattedorderItemDTO = this.formatOrderRefundDTO(this.orderItemDTO);
      fuzzyQueryOrderItem(formattedorderItemDTO).then(res => {
        this.tableData = res.data.list;
        this.total = res.data.total;
      })
    },
    formatOrderRefundDTO(orderItemDTO) {
      const formattedorderItemDTO = { ...orderItemDTO };
      if (formattedorderItemDTO.createdAt) {
        formattedorderItemDTO.createdAt = this.formatDate(formattedorderItemDTO.createdAt);
        console.log('格式化后的 createdAt:', formattedorderItemDTO.createdAt);
      }
      // if (formattedorderItemDTO.refundAt) {
      //   formattedorderItemDTO.refundAt = this.formatDate(formattedOrderRefundDTO.refundAt);
      //   console.log('格式化后的 refundAt:', formattedOrderRefundDTO.refundAt);
      // }
      return formattedorderItemDTO;
    },
    convertDateFields() {
      const dateFields = ['createdAt']
      dateFields.forEach(field => {
        if (this.orderItemDTO[field]) {
          this.orderItemDTO[field] = new Date(this.orderItemDTO[field])
        }
      })
    },
    formatDate(date) {
      if (!date) return null;
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    formatDates(orderRefund) {
      const formattedOrderRefund = { ...orderRefund };
      if (formattedOrderRefund.createdAt) {
        formattedOrderRefund.createdAt = this.formatDate(formattedOrderRefund.createdAt);
        console.log('格式化后的 createdAt:', formattedOrderRefund.createdAt);
      }
      if (formattedOrderRefund.refundAt) {
        formattedOrderRefund.refundAt = this.formatDate(formattedOrderRefund.refundAt);
        console.log('格式化后的 refundAt:', formattedOrderRefund.refundAt);
      }
      return formattedOrderRefund;
    },
    // 分页的两个绑定事件
    handleSizeChange(size) {
      this.orderItemDTO.pageSize = size
      this.findAll()
    }
    ,
    handleCurrentChange(currentPage) {
      this.orderItemDTO.pageNum = currentPage
      this.findAll()
    }
    ,
    // 跳转到指定页
    toPage() {
      this.findAll()
    }
    ,
    // 复选框点击事件
    handleSelectionChange(val) {
      this.multipleSelection = []
      for (let i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i].id)
      }
    }
    ,
    // 通过订单详情表中的id删除订单
    handleOrderItemDelete(index, row) {
      // 首先要进行弹框提示
      this.$confirm('是否确认删除订单详情编号为' + '"' + row.id + '"' + '的数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const orderItemId = row.id
        deleteOrderItem(orderItemId).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderItemDTO.pageNum = 1
            this.findAll()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    }
    ,
    // 批量删除订单
    deleteOrderItemBatch() {
      this.$confirm('是否确认删除选中的' + this.multipleSelection.length + '条数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrderItemBatch(this.multipleSelection).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderItemDTO.pageNum = 1
            this.findAll()
            // 批量删除成功后，需要清空已选择的行
            this.multipleSelection = []
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    }
    ,
    // 点击修改按钮，触发修改对话框
    handleOrderItemEdit(index, row) {
      // 先重置表单
      this.$refs.orderItemForm.resetFields()
      this.title = '修改订单详情'
      // 等待对话框完全打开
      this.$nextTick(() => {
        // 深拷贝数据
        this.orderItem = JSON.parse(JSON.stringify(row))
        this.editDialogVisible = true

      })
    }
    ,
    // 点击新增按钮，触发新增对话框
    handleAddOrderItem() {
      this.title = '添加订单详情'
      this.orderItem = {}
      this.editDialogVisible = true
      this.$refs.orderItemForm.resetFields() // 重置表单校验状态
    },
    // 点击保存按钮，触发保存事件
    saveOrderItem(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === '添加订单详情') {
            const formattedorderItem = this.formatDates(this.orderItem);
            addOrderItem(formattedorderItem).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '新增成功!',
                  duration: 1000
                })
                this.editDialogVisible = false
                this.orderItemDTO.pageNum = 1
                this.findAll()
                this.resetOrderItemForm('orderItemForm')
              } else {
                this.$message({
                  type: 'error',
                  message: '新增失败!',
                  duration: 1000
                })
              }
            })
          } else {
            updateOrderItem(this.orderItem).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '修改成功!',
                  duration: 1000
                })
                this.editDialogVisible = false
                this.orderItemDTO.pageNum = 1
                this.findAll()
                this.resetOrderItemForm('orderItemForm')
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败!',
                  duration: 1000
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetOrderItemForm(formName) {
      // 关闭对话框
      this.editDialogVisible = false
      // 延迟一下，确保表单控件都渲染完毕
      this.$nextTick(() => {
        this.$refs[formName].resetFields() // 重置表单校验状态
      })
    },

    // 上传前的回调，用于清空上次上传的文件列表
    beforeUpload(file) {
      this.fileList = [] // 清空文件列表
      return true
    },
    uploadExcelOrderItem() {
      const file = this.file
      // FormData是js对象,用于存储表单数据
      const formData = new FormData()
      formData.append('file', file) // 由后端接口决定,后端参数叫file
      // 封装的上传文件方法
      uploadExcel(formData).then((res) => {
        this.$message({
          message: '上传成功',
          type: 'success'
        })
        // 上传成功后添加到文件列表
        this.fileList.push({
          name: file.name
        }) // 上传成功后添加到文件列表
        this.uploadExcelDialog = false // 关闭弹窗
        this.orderItemDTO.pageNum = 1 // 刷新列表
        this.findAll() // 刷新列表
      })
    },
    // 监听文件改变
    handleChange(file) {
      this.file = file.raw
    },
    // 导出Excel订单详情数据
    exportOrderItem() {
      // 给出提示
      this.$confirm('是否确认导出订单详情数据？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 导出订单详情数据
        window.location.href = "http://localhost:8080/orderItem/exportOrderItem"
      }).catch(() => {
        // 取消操作
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    }
  },
  created() {
    this.findAll()
  }
}
</script>

<style>

</style>
